package com.app.utils;

import java.util.HashMap;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.RemoteViews;

import com.app.application.MyApplication;
import com.core.lib.application.BaseFragmentActivity;
import com.core.lib.core.ApiClient;
import com.core.lib.core.AsyncRequest;
import com.core.lib.core.HttpRequest;
import com.core.lib.core.HttpRequest.OnDownloadProgress;
import com.core.lib.utils.main.AppManager;
import com.core.lib.utils.main.StringUtilBase;
import com.core.lib.utils.main.UIHelper;
import com.core.lib.utils.main.UtilityBase;
import com.core.lib.widget.MyDialog;
import com.lepu.app.main.activity.AppBroswerActivity;
import com.lepu.app.main.activity.AppEnterWebGuideActivity;
import com.lepu.app.main.activity.MainTabActivity;
import com.lepu.app.main.bean.BeanCheckVersion;
import com.lepu.pasm.R;

/**
 *
 * @author wuxd 通用检查更新的类
 *
 */
public class UpdateManager implements AsyncRequest {

	public static final int REQUEST_CODE = 1000;

	private static final String REQUEST_CHECK_UPDATE = "request_check_update";

	private static final int MSG_CHECK_SUCCESS = 10;
	private static final int MSG_CHECK_FAIL = 11;

	private static UpdateManager mUpdateManager = null;
	private BaseFragmentActivity mCurrentActivity = null;

	private boolean mNeedProgress = false;

	private NotificationManager mNotificationManager = null;
	private Notification mNotification = null;
	private boolean mIsDownload = false;

	private UpdateManager() {
	}

	public static UpdateManager getInstance() {
		if (mUpdateManager == null) {
			mUpdateManager = new UpdateManager();
		}

		return mUpdateManager;
	}

	public void checkUpdate(boolean isAppStart, String url,
							BaseFragmentActivity context, boolean needProgress,
							boolean needNetToast) {

		if (mNotificationManager == null) {
			mNotificationManager = (NotificationManager) context
					.getSystemService(Context.NOTIFICATION_SERVICE);
		}

		mNeedProgress = needProgress;
		mCurrentActivity = context;

		if (mNeedProgress) {
			if (context instanceof BaseFragmentActivity) {
				((BaseFragmentActivity) context).showProgressDialog();
			}
		}

		int versionCode = 0;
		try {
			versionCode = context.getPackageManager().getPackageInfo(
					context.getPackageName(), 0).versionCode;
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}

		checkUpdate(isAppStart, url, versionCode, needNetToast);
	}

	private void checkUpdate(boolean isAppStart, String url, int versionCode,
							 boolean needNetToast) {

		Map<String, Object> map = new HashMap<String, Object>();
		JSONObject params = new JSONObject();
		try {
			params.put("DeviceID", Setting.DEVICEID);
			params.put("ApplicationID", Setting.APPLICATIONID);
			params.put("VersionCode", versionCode);
			params.put("AppType", "Patient");//月子不需要这个参数
			params.put("Language","zh-CN");

			String umengChannel = UtilityBase.getAppMetedata(mCurrentActivity,
					"UMENG_CHANNEL");
			params.put("AppChannel", umengChannel);

			if (isAppStart) {
				params.put("UserID", LoginUtil.getUserId());
				params.put("LoginToken", LoginUtil.getLoginToken());
				params.put("BaiduUserID",
						MyApplication.getInstance().mBaiduUserId);
				params.put("BaiduChannelID",
						MyApplication.getInstance().mBaiduChannelId);
				params.put("GeTuiCID", MyApplication.getInstance().mGeTuiChannelId);
				params.put("BranchID", Setting.getBranchID(mCurrentActivity));

				params.put("ClientOSVersion",
						AppManager.getDeviceSdkVersion(mCurrentActivity));
				params.put("DeviceModel",
						AppManager.getDeviceModel(mCurrentActivity));
				params.put("DeviceSN",
						AppManager.getDeviceUniqueId(mCurrentActivity));
				params.put("ClientIP",
						AppManager.getDeviceIpAddress(mCurrentActivity));

				params.put("Longitude", LocationUtil.getInstance().mLongitude);//经度
				params.put("Latitude", LocationUtil.getInstance().mLatitude);//纬度
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
		map.put("ht", params);

		ApiClient.http_post(url, map, null, this, REQUEST_CHECK_UPDATE,
				needNetToast, needNetToast);
	}

	@SuppressLint("HandlerLeak")
	private Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
				case MSG_CHECK_SUCCESS:

					if (mNeedProgress) {
						mCurrentActivity.hideProgressDialog();
					}

					BeanCheckVersion beanCheckVersion = (BeanCheckVersion) msg.obj;
					int ClientUpgrade = UtilityBase.parseInt(beanCheckVersion.ClientUpgrade);
					if (beanCheckVersion != null
							&& ClientUpgrade > 0) {
						showUpdateVersionDialog(beanCheckVersion);
					}

					break;
				case MSG_CHECK_FAIL:

					if (mNeedProgress) {
						mCurrentActivity.hideProgressDialog();

						//UIHelper.showToast(mCurrentActivity, R.string.check_network);
					}
					break;
				default:
					break;
			}
		};
	};

	// update app,download
	public void showUpdateVersionDialog(final BeanCheckVersion beanCheckVersion) {

		StringBuffer sb = new StringBuffer();
		sb.append(String
				.format("新版本：V%s", beanCheckVersion.ClientLatestVersion));
		sb.append("\n\r");
		sb.append("\n\r");
		sb.append(beanCheckVersion.ClientUpgradeMemo);

		Activity currentActivity = AppManager.getAppManager().currentActivity();
		if (currentActivity instanceof AppEnterWebGuideActivity) {
			currentActivity = MainTabActivity.getInstance();
		}

		MyDialog dialog = new MyDialog(currentActivity);
		dialog.setTitle(R.string.app_update_title);
		dialog.setMessage(sb.toString());

		int ClientUpgrade = UtilityBase.parseInt(beanCheckVersion.ClientUpgrade);
		if(ClientUpgrade == 1)
		{
			dialog.setNegativeButton(R.string.app_update_now_cancel,
					new View.OnClickListener() {

						@Override
						public void onClick(View v) {

						}
					});
		}

		dialog.setPositiveButton(R.string.app_update_now_ok,
				new View.OnClickListener() {

					@Override
					public void onClick(View v) {

						if (mIsDownload) {
							return;
						}

						String ClientDownloadUrl = beanCheckVersion.ClientDownloadUrl;

						if (!StringUtilBase.stringIsEmpty(ClientDownloadUrl)) {
							if (ClientDownloadUrl.endsWith("apk")) {
								Intent openIntent = new Intent(
										mCurrentActivity, MainTabActivity.class);
								showNotification(R.drawable.app_icon,
										R.string.app_name, openIntent);
								showDownloadFileDialog(ClientDownloadUrl);
							} else {
								Intent openIntent = new Intent(
										mCurrentActivity,
										AppBroswerActivity.class);
								openIntent.putExtra("url", ClientDownloadUrl);
								openIntent.putExtra("title", "");
								mCurrentActivity
										.startActivity(openIntent, true);
							}
						}
					}
				});
		dialog.create(null);

		if(ClientUpgrade == 2)
		{
			dialog.setCancelable(false);
			dialog.setCanceledOnTouchOutside(false);
			dialog.setClickDismiss(false);
		}

		dialog.showMyDialog();
	}

	/*
	 * 下载程序
	 */
	public void showDownloadFileDialog(String downloadUrl) {

		// download
		String filePath = SdLocal.getDownloadApkPath(mCurrentActivity,
				mCurrentActivity.getString(R.string.app_name));

		HttpRequest.downloadFile(downloadUrl, filePath,
				new OnDownloadProgress() {

					@Override
					public void onProgressChanged(int progress) {
						Message msg = new Message();
						msg.what = MSG_PROGRESS_CHANGED;
						msg.arg1 = progress;
						mProgressHandler.sendMessage(msg);
					}

					@Override
					public void onError(Exception e) {
						mProgressHandler.sendEmptyMessage(MSG_PROGRESS_ERROR);
					}
				});
	}

	public static final int MSG_PROGRESS_CHANGED = 100;
	public static final int MSG_PROGRESS_ERROR = 101;

	@SuppressLint("HandlerLeak")
	private Handler mProgressHandler = new Handler() {

		@SuppressLint("HandlerLeak")
		public void handleMessage(Message msg) {

			switch (msg.what) {
				case MSG_PROGRESS_CHANGED:

					if (MainTabActivity.getInstance() == null)
						return;

					int progress = msg.arg1;

					mIsDownload = true;

					if (progress > 0) {
						mNotification.contentView.setProgressBar(R.id.progressBar,
								100, progress, false);
						mNotification.contentView.setTextViewText(
								R.id.notification_textview, progress + "%");
					}

					mNotificationManager.notify(R.string.app_name, mNotification);

					if (progress == 100) {

						UtilityBase.installApk(mCurrentActivity, SdLocal
								.getDownloadApkPath(mCurrentActivity,
										mCurrentActivity
												.getString(R.string.app_name)));
						deleteNotification();
					}

					break;
				case MSG_PROGRESS_ERROR:
					UIHelper.showToast(mCurrentActivity,
							R.string.update_download_apk_fail);
					break;
				default:
					break;
			}

		};
	};

	public void deleteNotification() {
		mIsDownload = false;
		// 删除通知
		if (mNotificationManager != null) {
			mNotificationManager.cancel(R.string.app_name);
		}
	}

	@SuppressWarnings("deprecation")
	public void showNotification(int iconId, int notifyId, Intent openIntent) {

		long when = System.currentTimeMillis();

		mNotification = new Notification(iconId, "更新 ", when);
		// mNotification.defaults = Notification.DEFAULT_SOUND;// 发出默认声音

		RemoteViews rv = new RemoteViews(mCurrentActivity.getPackageName(),
				R.layout.main_update_notification);
		rv.setProgressBar(R.id.progressBar, 100, 0, false);
		rv.setImageViewResource(R.id.ImageView, iconId);
		rv.setTextViewText(R.id.notification_textview, "0%");
		PendingIntent contentIntent = PendingIntent.getActivity(
				mCurrentActivity, REQUEST_CODE, openIntent,
				PendingIntent.FLAG_UPDATE_CURRENT);// 当点击消息时就会向系统发送openintent意图

		mNotification.contentView = rv;
		mNotification.contentIntent = contentIntent;
		mNotificationManager.notify(notifyId, mNotification);// 第一个参数为自定义的通知唯一标识
	}

	@Override
	public void RequestComplete(Object object, Object data) {
		if (object.equals(REQUEST_CHECK_UPDATE)) {

			BeanCheckVersion checkVersion = BeanCheckVersion
					.parseCheckVersion((String) data);

			Message msg = mHandler.obtainMessage();
			msg.what = MSG_CHECK_SUCCESS;
			msg.obj = checkVersion;
			mHandler.sendMessage(msg);
		}
	}

	@Override
	public void RequestError(Object object, int errorId, String errorMessage) {
		if (object.equals(REQUEST_CHECK_UPDATE)) {
			mHandler.sendEmptyMessage(MSG_CHECK_FAIL);
		}
	}

}
